<?php
class LogFormBehavior extends CActiveRecordBehavior
{
    public $tableName = 'form_submission_log';
    
    private $_formId;
    
    protected function getFormId()
    {
        if ($this->_formId === null)
        {
            $form = Form::model()->findByAttributes(array('table_name'=>$this->getOwner()->tableName()));
            if (is_object($form))
                $this->_formId = $form->id;
            else
                $this->_formId = 0;
        }
        return $this->_formId;
    }
    
    public function beforeSave()
    {
        /** @var CDbCommand */
        $command = $this->getOwner()->getDbConnection()->createCommand();
        $command->insert($this->tableName, array(
            'form_id'=>$this->getFormId(),
            'submitted_date'=>date('Y-m-d H:i:s'),
            'ip'=>Yii::app()->request->getUserHostAddress(),
            'user_agent'=>Yii::app()->request->getUserAgent(),
            'successful'=>0,
        ));
    }
    
    public function afterSave()
    {
        /** @var CDbCommand */
        $command = $this->getOwner()->getDbConnection()->createCommand();
        $command->insert($this->tableName, array(
            'form_id'=>$this->getFormId(),
            'submitted_date'=>date('Y-m-d H:i:s'),
            'ip'=>Yii::app()->request->getUserHostAddress(),
            'user_agent'=>Yii::app()->request->getUserAgent(),
            'successful'=>1,
        ));
    }
}